﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TaskManager
{
    // 此控件用于实现任务状态分栏展示功能，分为未完成和已完成的任务
    public partial class TaskSelect : UserControl
    {
        int SPACE1 = 5, SPACE2 = 15;    // 间距

        public TaskSelect()
        {
            InitializeComponent();
            //updateSize();   // 更新显示尺寸

            //flowLayoutPanel_main.BackColor = Color.FromArgb(255, 203, 254, 197);

            //preSelectedIteam = selectedIteam = checkIteam_new;
            //checkIteam_new.This_Selected += new TaskManager.checkIteam.select_Handle(this.checkIteam_SelectedChanged);        // 为控件添加选中处理逻辑
        }

        // 定义两个变量数组分别用于存储未完成和已完成的任务列表信息
        public Dictionary<String, checkIteam> unfinishTask = new Dictionary<string, checkIteam>();
        public Dictionary<String, checkIteam> finishedTask = new Dictionary<string, checkIteam>();

        public delegate void contextMenu_Handle(object sender, EventArgs e, String menuName, checkIteam selectedIteam);
        [Description("当前控件的右键弹出菜单响应处理逻辑"), Category("自定义事件")]
        public event contextMenu_Handle ContextMenuClick;

        private void checkIteams_ContextMenuClick(String menuName)
        {
            if(ContextMenuClick != null) ContextMenuClick(this, new EventArgs(), menuName, selectedIteam);
        }

        // 调用查看菜单处理逻辑
        private void 查看ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            checkIteams_ContextMenuClick("查看");
        }


        private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            checkIteams_ContextMenuClick("编辑");
        }


        public delegate void check_Handle(object sender, EventArgs e, checkIteam iteam);
        [Description("当有子控件checkIteam.Checked的选中状态变动时发生"), Category("自定义事件")]
        public event check_Handle CheckedChanged;

        // 此处为所有checkIteam的事件处理逻辑，调用自定义事件CheckedChanged
        private void checkIteams_CheckedChanged(object sender)
        {
            checkIteam iteam = (checkIteam)sender;

            removeCheckIteam(iteam.Data);   // 从现有控件中移除
            addCheckIteam(iteam);           // 根据控件的checked状态添加到当前控件中

            //checkIteam tmp = addCheckIteam(iteam.ShowText, iteam.ShowTextColor, iteam.Checked, iteam.Data, iteam.NoteText, iteam.NoteColor);
            //tmp.Selected = iteam.Selected;
            //if (selectedIteam == iteam) selectedIteam = tmp;

            //MessageBox.Show("子控件选中状态变动为:" + iteam.Checked + ", 附加信息：" + iteam.Data);
            //MessageBox.Show("TaskSelect.cs  checkIteams_CheckedChanged ");

            if (CheckedChanged != null) // 调用状态变动处理逻辑
            {
                CheckedChanged(this, new EventArgs(), iteam);
                //MessageBox.Show("子控件选中状态变动为:" + isChecked + ", 附加信息：" + data);
            }
        }

        private checkIteam preSelectedIteam;    // 记录前一个选中控件
        private checkIteam selectedIteam;       // 用于记录当前选中的checkIteam项
        [Description("鼠标点击时，选中的checkIteam"), Category("自定义属性")]
        public checkIteam SelectedIteam
        {
            get
            {
                return selectedIteam;
            }
            set
            {
                selectedIteam = value;
            }
        }

        public delegate void button_Handle(object sender, EventArgs e, checkIteam iteam);
        [Description("当按钮点击时发生"), Category("自定义事件")]
        public event button_Handle ButtonClicked;

        // 按钮点击时，调用此逻辑
        private void button_click(object sender, EventArgs e, checkIteam iteam)
        {
            if (ButtonClicked != null)
            {
                ButtonClicked(sender, e, iteam);
            }
        }

        public delegate void doubleClick_Handle(object sender, EventArgs e);
        [Description("当双击子控件CheckIteam时发生，调用当前控件逻辑"), Category("自定义事件")]
        public event doubleClick_Handle Double_Click;

        private void checkIteam_DoubleClick(object sender, EventArgs e)
        {
            if (Double_Click != null) Double_Click(sender, e);
        }

        public delegate void select_Handle(object sender);
        [Description("每当选中的CheckeIteam项变动时发生"), Category("自定义事件")]
        public event select_Handle SelectedChanged;


        // 选中的子控件变动处理逻辑，调用自定义事件CheckedChanged
        private void checkIteam_SelectedChanged(object sender)
        {
           
            selectedIteam = (checkIteam)sender; // 记录当前选中的checkIteam
            //MessageBox.Show("当前选中任务：" + selectedIteam.ShowText);
            selectIteam(selectedIteam);         // 仅选中当前点击的控件
            preSelectedIteam = selectedIteam;   // 记录前一次选中的控件

            if (SelectedChanged != null) SelectedChanged(sender);
        }

        // 选中控件iteam
        public void selectIteam(checkIteam iteam)
        {
            if (iteam == null ||iteam == preSelectedIteam) return;

            //checkIteam preSelect = selectedIteam;
            if (preSelectedIteam != null)
            {
                preSelectedIteam.Selected = false;  // 取消前一次选中控件的选择状态
            }

            // 设置控件iteam为选中状态
            if (iteam.Checked) finishedTask[iteam.Data].Selected = true;
            else unfinishTask[iteam.Data].Selected = true;
        }

        public checkIteam addCheckIteam(String Text, Color TextColor, bool topMost, TYPE type)
        {
            return addCheckIteam(Text, TextColor, topMost, DateTime.Now.Millisecond + "", type);
        }

        // 根据checkIteam的选中状态，添加到到当前控件中
        public checkIteam addCheckIteam(checkIteam iteam)
        {
            if (iteam.Checked)
            {
                finishedTask.Add(iteam.Data, iteam);
                flowLayoutPanel_finish.Controls.Add(iteam);
            }
            else
            {
                unfinishTask.Add(iteam.Data, iteam);
                flowLayoutPanel_unfinish.Controls.Add(iteam);
                
            }

            return iteam;
        }

        //public bool isBatchAddIteams = false;  // 标识当前是否处于批量添加状态

        // 向控件中添加任务信息
        public checkIteam addCheckIteam(String Text, Color TextColor, bool topMost, String data, TYPE type, String noteText, Color noteColor)
        {
            if (!unfinishTask.Keys.Contains(data) && !finishedTask.Keys.Contains(data))
            {
                checkIteam iteam = new checkIteam(Text, topMost, data, type, noteText, noteColor);
                iteam.Width = panel_main.ClientSize.Width - SPACE1;

                iteam.CheckedChanged += new TaskManager.checkIteam.checkBox_Handle(this.checkIteams_CheckedChanged);    // 为控件选中状态添加处理逻辑
                iteam.This_Selected += new TaskManager.checkIteam.select_Handle(this.checkIteam_SelectedChanged);       // 为控件添加选中处理逻辑
                iteam.ButtonClicked += new TaskManager.checkIteam.button_Handle(this.button_click);                     // 为控件添加按钮点击处理逻辑
                iteam.DoubleClick_M += new TaskManager.checkIteam.doubleClick_Handle(this.checkIteam_DoubleClick);      // 为控件添加按钮双击处理逻辑

                if (!topMost) unfinishTask.Add(data, iteam);
                else finishedTask.Add(data, iteam);

                if (!topMost) flowLayoutPanel_unfinish.Controls.Add(iteam);
                else flowLayoutPanel_finish.Controls.Add(iteam);

                //if (iteam.Width > main_width)       // 更新显示为最大尺寸
                //{
                //    main_width = iteam.Width;
                //    flowLayoutPanel_main.Width = main_width;
                //}

                //if(!isBatchAddIteams) updateSize();   // 更新显示尺寸

                return iteam;
            }
            return null;
        }

        public checkIteam addCheckIteam(String Text, Color TextColor, bool topMost, String data, TYPE type)
        {
            if (!unfinishTask.Keys.Contains(data) && !finishedTask.Keys.Contains(data))
            {
                checkIteam iteam = new checkIteam(Text, topMost, data, type);
                iteam.Width = panel_main.ClientSize.Width - SPACE1;

                iteam.CheckedChanged += new TaskManager.checkIteam.checkBox_Handle(this.checkIteams_CheckedChanged);    // 为控件选中状态添加处理逻辑
                iteam.This_Selected += new TaskManager.checkIteam.select_Handle(this.checkIteam_SelectedChanged);       // 为控件添加选中处理逻辑
                iteam.ButtonClicked += new TaskManager.checkIteam.button_Handle(this.button_click);                     // 为控件添加按钮点击处理逻辑
                iteam.DoubleClick_M += new TaskManager.checkIteam.doubleClick_Handle(this.checkIteam_DoubleClick);      // 为控件添加按钮双击处理逻辑

                if (!topMost) unfinishTask.Add(data, iteam);
                else finishedTask.Add(data, iteam);

                if (!topMost) flowLayoutPanel_unfinish.Controls.Add(iteam);
                else flowLayoutPanel_finish.Controls.Add(iteam);

                //if (iteam.Width > main_width)       // 更新显示为最大尺寸
                //{
                //    main_width = iteam.Width;
                //    flowLayoutPanel_main.Width = main_width;
                //}

                //if (!isBatchAddIteams) updateSize();   // 更新显示尺寸

                return iteam;
            }
            return null;
        }

        //// 向控件中添加任务信息
        //public checkIteam addCheckIteam(String Text, Color TextColor, bool unFinish, String data, TYPE type, String noteText, Color noteColor)
        //{
        //    checkIteam iteam = addCheckIteam(Text, TextColor, unFinish, data, type);
        //    iteam.NoteText = noteText;
        //    iteam.NoteColor = noteColor;

        //    return iteam;
        //}

        // 移除控件中的某项任务信息
        public bool removeCheckIteam(String data)
        {
            // 从未完成任务列表中移除对应数据的任务信息
            if (unfinishTask.Keys.Contains(data))
            {
                checkIteam iteam = unfinishTask[data];
                flowLayoutPanel_unfinish.Controls.Remove(iteam);
                unfinishTask.Remove(data);

                return true;
            }
            // 从已完成任务列表中移除对应数据的任务信息
            else if (finishedTask.Keys.Contains(data))
            {
                checkIteam iteam = finishedTask[data];
                flowLayoutPanel_finish.Controls.Remove(iteam);
                finishedTask.Remove(data);

                return true;
            }
            return false;
        }

        // 清空任务列表信息
        public void clear()
        {
            // 移除任务信息控件
            flowLayoutPanel_unfinish.Controls.Clear();
            flowLayoutPanel_finish.Controls.Clear();

            // 移除任务信息
            unfinishTask.Clear();
            finishedTask.Clear();

            //isBatchAddIteams = true;
        }

        //// 更新尺寸信息
        //public void updateSize()
        //{
        //    //getMaxWidth();
        //    getMaxHeight();

        //    //flowLayoutPanel_main.Width = main_width;
        //    flowLayoutPanel_main.Height = main_height;
        //    flowLayoutPanel_main.Width = panel_main.Width-25;
        //    updatecheckIteamsWidth();

        //    splitLineHorizontal1.Width = panel_main.Width - 35;
        //    splitLineHorizontal1.Invalidate();

        //    isBatchAddIteams = false;
        //}

        //// 重置所有checkIteam的宽度
        //public void updatecheckIteamsWidth()
        //{
        //    int width = flowLayoutPanel_main.Width - 3;
        //    foreach (Control T in flowLayoutPanel_unfinish.Controls)
        //    {
        //        checkIteam tmp = (checkIteam)T;
        //        tmp.setWidth(width);
        //    }

        //    foreach (Control T in flowLayoutPanel_finish.Controls)
        //    {
        //        checkIteam tmp = (checkIteam)T;
        //        tmp.setWidth(width);
        //    }
        //}

        //// 获取当前控件的最大checkIteam宽度
        //public void getMaxWidth()
        //{
        //    int max = 0;

        //    foreach (Control T in flowLayoutPanel_unfinish.Controls)
        //    {
        //        checkIteam tmp = (checkIteam)T;
        //        if (tmp.Width > max) max = tmp.Width;
        //    }

        //    foreach (Control T in flowLayoutPanel_finish.Controls)
        //    {
        //        checkIteam tmp = (checkIteam)T;
        //        if (tmp.Width > max) max = tmp.Width;
        //    }

        //    main_width = max;
        //}

        //// 获取当前控件的最大checkIteam宽度
        //public void getMaxHeight()
        //{
        //    int max = 0;
        //    foreach (Control T in flowLayoutPanel_finish.Controls)
        //    {
        //        checkIteam tmp = (checkIteam)T;
        //        if (tmp.Width > max) max = tmp.Width;
        //    }

        //    int count = flowLayoutPanel_unfinish.Controls.Count + flowLayoutPanel_finish.Controls.Count + 2;
        //    main_height = count*32;
        //}


        private void panel_main_Click(object sender, EventArgs e)
        {
            if (selectedIteam != null) selectedIteam.Selected = false; //取消CheckIteam的选中状态
        }

        // 控件尺寸变动时，修改子控件尺寸
        private void panel_main_SizeChanged(object sender, EventArgs e)
        {
            //updateSize();
        }


        private void TaskSelect_Paint(object sender, PaintEventArgs e)
        {
            updateSize();
        }

        public void updateSize()
        {
            int W = panel_main.ClientSize.Width - SPACE1;
            int H = 32 * (flowLayoutPanel_unfinish.Controls.Count + flowLayoutPanel_finish.Controls.Count + 2);

            // 设置内容面板的尺寸
            flowLayoutPanel_main.Width = W;
            flowLayoutPanel_main.Height = H;

            // 设置分割线宽度
            splitLineHorizontal1.Width = W - SPACE2;

            // 未完成任务显示宽度
            foreach (Control iteam in flowLayoutPanel_unfinish.Controls)
            {
                iteam.Width = W;
            }

            // 已完成任务显示宽度
            foreach (Control iteam in flowLayoutPanel_finish.Controls)
            {
                iteam.Width = W;
            }
        }

        // ----------------------------------------辅助功能函数-------------------------------------
        

        //// 在当前控件中显示任务信息
        //public void setTaskInfo(List<string[]> taskInfoData)
        //{
        //    clear();

        //    addTaskInfo(taskInfoData);

        //    updateSize();   // 更新显示尺寸
        //}

        // 在控件中显示Task信息
        public void addInfo(List<Data_Task> TaskData, TabMode Mode)
        {
            string timeNow = Tool.TimeNow();        // 获取当前时间
            int minute = -1 * loginForm.settings.minute_Before_TaskDeadline;
            int second = loginForm.settings.second_Refresh_Intervate;

            int opendbyme_FinshedNum = 0;           // 由我创建的任务完成数目
            foreach (Data_Task Task in TaskData)
            {
                if (
                    Mode == TabMode.ALL ||
                    (Mode == TabMode.AssignedTo && Task.assignedTo.Equals(loginForm.userName)) ||
                    (Mode == TabMode.MailTo && Task.mailto.Contains("," + loginForm.userName + ",")) ||
                    (Mode == TabMode.OpenedBy && Task.openedBy.Equals(loginForm.userName))
                    )
                {
                    String data = Task.id;
                    String Text = Task.name;
                    Color TextColor = Color.Black;

                    String state = Tool.toCN(Task.status);
                    if (state.Equals("进行中"))    // 对进行中的任务判定是否超时
                    {
                        //string deadline = Tool.ToString(Tool.parseDate(timeNow).AddMinutes(10));

                        if (Tool.Date_cmp(timeNow, Task.deadline) > 0)
                            state = "（超时）";
                        else if (Tool.DateInRegion(timeNow, Task.deadline, minute, second))    // 当前时间在截止时间的前10分钟的20s内
                            state = "（将到期）";

                        //if(Tool.Shortdate_cmp(DateTime.Now.ToShortDateString(), Task.deadline) > 0)
                        //    state = "（超时）";
                    }

                    Color noteColor = Tool.getColor(state);
                    bool finishState = Tool.getUnFinished(state);

                    addCheckIteam(Text, TextColor, finishState, data, TYPE.Task, state, noteColor);

                    // 统计由我创建任务的完成数目
                    if (finishState && Task.openedBy.Equals(loginForm.userName)) opendbyme_FinshedNum++;
                }
            }

            // 存在多个创建的任务已完成时，提示清理
            if (opendbyme_FinshedNum >= 10)
            {
                String tipInfo = "   “由我创建”的任务有" + opendbyme_FinshedNum + "个已完成，请双击已完成的任务，在打开的网页中点击关闭。\r\n\r\n   即时关闭已完成的任务，可有效避免显示卡顿！" +
                    "\r\n\r\n   （也可在禅道网页端，我的地盘->任务->指派给我、抄送给我、由我创建 中进行关闭）";
                new NoticeForm(Tool.DateString(), TYPE.Tip, "请关闭已完成的任务", "NEW", tipInfo).TipId_CheckShow();  // 任务完成关闭提示信息
            }
        }


        // 在控件中显示Demand信息
        public void addInfo(List<Data_Demand> DemandData, TabMode Mode)
        {
            foreach (Data_Demand Demand in DemandData)
            {
                if (
                    Mode == TabMode.ALL ||
                    (Mode == TabMode.AssignedTo && Demand.assignedTo.Equals(loginForm.userName)) ||
                    (Mode == TabMode.MailTo && Demand.mailto.Contains("," + loginForm.userName)) ||
                    (Mode == TabMode.OpenedBy && Demand.openedBy.Equals(loginForm.userName))
                    )
                {
                    String data = Demand.id;
                    String Text = Demand.title;
                    Color TextColor = Color.Black;

                    String state = Tool.toCN(Demand.stage);
                    Color noteColor = Tool.getColor(state);
                    bool finishState = Tool.getUnFinished(state);

                    addCheckIteam(Text, TextColor, finishState, data, TYPE.Demand, state, noteColor);
                }
            }
        }


        // 在控件中显示Bug信息
        public void addInfo(List<Data_Bug> BugData, TabMode Mode)
        {
            foreach (Data_Bug Bug in BugData)
            {
                if (
                    Mode == TabMode.ALL ||
                    (Mode == TabMode.AssignedTo && Bug.assignedTo.Equals(loginForm.userName)) ||
                    (Mode == TabMode.MailTo && Bug.mailto.Contains("," + loginForm.userName)) ||
                    (Mode == TabMode.OpenedBy && Bug.openedBy.Equals(loginForm.userName))
                    )
                {
                    String data = Bug.id;
                    String Text = Bug.title;
                    Color TextColor = Color.Black;

                    String state = Tool.toCN(Bug.status);
                    Color noteColor = Tool.getColor(state);
                    bool finishState = Tool.getUnFinished(state);

                    addCheckIteam(Text, TextColor, finishState, data, TYPE.Bug, state, noteColor);
                }
            }
        }

        // 在控件中显示Testtask信息
        public void addInfo(List<Data_Testtask> TesttaskData, TabMode Mode)
        {
            foreach (Data_Testtask Testtask in TesttaskData)
            {
                if (
                    Mode == TabMode.ALL ||
                    (Mode == TabMode.AssignedTo && Testtask.owner.Equals(loginForm.userName)) ||
                    (Mode == TabMode.MailTo && Testtask.mailto.Contains("," + loginForm.userName + ","))
                    //|| (Mode == TabMode.OpenedBy && Testtask.owner.Equals(loginForm.userName))
                    )
                {
                    String data = Testtask.id;
                    String Text = Testtask.name;
                    Color TextColor = Color.Black;

                    String state = Tool.toCN(Testtask.status);
                    Color noteColor = Tool.getColor(state);
                    bool finishState = Tool.getUnFinished(state);

                    addCheckIteam(Text, TextColor, finishState, data, TYPE.Testtask, state, noteColor);
                }
            }
        }

        // 在控件中显示Daily信息
        public void addInfo(List<Data_Daily> DailyData, TabMode Mode)
        {
            foreach (Data_Daily Daily in DailyData)
            {
                if (Mode == TabMode.ALL || Mode == TabMode.Daily)
                {
                    String data = Daily.id;
                    String Text = Daily.work;
                    Color TextColor = Color.Black;

                    String state = Tool.toCN(Daily.dstatus);
                    Color noteColor = Tool.getColor(state);
                    bool finishState = Tool.getUnFinished(state);

                    addCheckIteam(Text, TextColor, finishState, data, TYPE.Daily, state, noteColor);
                }
            }
        }




        //// 在 TaskSelect控件中显示任务信息
        //public void addTaskInfo(List<string[]> taskInfoData)
        //{
        //    foreach (string[] task in taskInfoData)
        //    {
        //        String data = task[0];
        //        String Text = task[1];
        //        Color TextColor = Color.Black;

        //        String state = task[2];
        //        Color noteColor = Tool.getColor(state);
        //        bool finishState = Tool.getUnFinished(state);

        //        addCheckIteam(Text, TextColor, finishState, data, state, noteColor);
        //    }
        //}


    }
}
